package com.vikutorika.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.apache.taglibs.standard.tag.common.sql.DataSourceUtil;

import javax.sql.DataSource;
import java.sql.*;
import java.util.Properties;

public class V_DBUtils {
    private static DataSource dataSource;
    static{
        try {
            Properties properties = new Properties();
            properties.load(DataSourceUtil.class.getResourceAsStream("/vikutorika.properties"));
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    /**
     * 标准化关闭连接
     * @param rs 结果集
     * @param pstmt PreparedStatement
     * @param conn 连接池连接
     */
    public static void close(ResultSet rs, PreparedStatement pstmt, Connection conn) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (pstmt != null) {
                pstmt.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    public static void close(Connection conn) {
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 可以直接将结果集格式化打印出来
     * @param resultSet 要打印的结果集
     */
    public static void printResult(ResultSet resultSet) {
        if (resultSet != null) {
            try {
                ResultSetMetaData metaData = resultSet.getMetaData();
                int columnCount = metaData.getColumnCount();

                for (int i = 1; i <= columnCount; i++) {
                    System.out.printf("%-12s", metaData.getColumnLabel(i));
                }

                System.out.println();
                System.out.println(String.format("%" + columnCount * 12 + "s", "-").replace(" ", "-"));
                while (resultSet.next()) {
                    for (int i = 1; i <= columnCount; i++) {
                        System.out.printf("%-12s", resultSet.getString(i));
                    }
                    System.out.println();
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
